package com.cool4j.generator.util

import com.cool4j.generator.config.DBConstants
import com.cool4j.generator.config.GeneratorConstants
import com.cool4j.view.Activator
import com.cool4j.view.entity.PreferenceVO
import com.cool4j.view.entity.TableItemControl
import freemarker.template.Template
import freemarker.template.TemplateException
import org.apache.commons.lang3.StringUtils
import org.eclipse.core.runtime.Platform
import org.eclipse.jface.preference.PreferenceStore
import org.eclipse.swt.SWT
import org.eclipse.swt.custom.TableEditor
import org.eclipse.swt.graphics.Image
import org.eclipse.swt.widgets.Button
import org.eclipse.swt.widgets.Table
import org.eclipse.swt.widgets.TableItem
import org.eclipse.swt.widgets.Text

/**
 * 代码生成器操作工具类
 *
 * @author Frank create on 16/1/8 09:56
 */
final class GeneratorUtil {

    /**
     * 执行模板,并将数据写入文件
     *
     * @param filePath - 文件写入路径
     * @param template - 模板
     * @param tableData - 需要的数据
     * @throws TemplateException - 模板异常
     * @throws IOException - IO 异常
     */
    static void writeFile(String filePath, Template template, Map<String, Object> tableData) throws TemplateException, IOException {
        // 判断文件夹是否存在,如果不存在自动创建文件夹
        def dirPath = filePath.substring(0, filePath.lastIndexOf("/"))
        def file = new File(dirPath)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs()
        }
        def out = new FileOutputStream(filePath, false)
        def writer = new OutputStreamWriter(out, "UTF-8")
        template.process(tableData, writer)
        writer.flush()
        writer.close()
        out.close()
    }

    /**
     * 根据图片名称获取图片对象
     *
     * @param imageName - 图片名称
     * @return - 图片对象
     */
    static Image getImage(String imageName) {
        def image = Activator.getImageDescriptor("icons/" + imageName).createImage()
        return image
    }

    /**
     * 获取首选项配置文件存放路径
     *
     * @return 首选项配置文件路径
     */
    static String getPreferenceStoreFile() {
        return Activator.getDataFolder() + "setting.properties"
    }

    /**
     * 获取默认的代码输出路径: workspace 下的 output 目录
     *
     * @return - 默认的代码输出路径
     */
    static String getDefaultOutputPath() {
        def workspacePath = Platform.getInstanceLocation().getURL().getPath()
        workspacePath.replace("\\", "/")
        return workspacePath + "output"
    }

    /**
     * 读取首选项配置值,如果没有配置文件则取默认值
     *
     * @return - 首选项配置 VO
     */
    static PreferenceVO readPreferenceProperties() {
        def propertyFilePath = getPreferenceStoreFile()
        def propertyFile = new File(propertyFilePath)
        if (!propertyFile.exists()) {
            return getDefaultPreference()
        } else {
            def preferenceStore = new PreferenceStore(getPreferenceStoreFile())
            try {
                preferenceStore.load()
                def preferenceVO = new PreferenceVO()
                preferenceVO.setUsername(preferenceStore.getString(DBConstants.DB_FIELD_USERNAME))
                preferenceVO.setPassword(preferenceStore.getString(DBConstants.DB_FIELD_PASSWORD))
                preferenceVO.setUrl(preferenceStore.getString(DBConstants.DB_FIELD_URL))
                preferenceVO.setDriver(preferenceStore.getString(DBConstants.DB_FIELD_DRIVER))
                preferenceVO.setAuthor(preferenceStore.getString(GeneratorConstants.FIELD_AUTHOR))
                preferenceVO.setEntitySuffix(preferenceStore.getString(GeneratorConstants.FIELD_ENTITY_SUFFIX))
                preferenceVO.setCommonPackage(preferenceStore.getString(GeneratorConstants.FIELD_COMMON_PACKAGE_PATH))
                preferenceVO.setPackagePath(preferenceStore.getString(GeneratorConstants.FIELD_PACKAGE_PATH))
                preferenceVO.setOutputPath(preferenceStore.getString(GeneratorConstants.FIELD_OUTPUT_PATH))
                return preferenceVO
            } catch (IOException e) {
                e.printStackTrace()
            }
        }
        return null
    }

    /**
     * 获取默认首选项配置值
     *
     * @return - 首选项配置 VO(默认值)
     */
    static PreferenceVO getDefaultPreference() {
        def outputPathValue = getDefaultOutputPath()
        if (outputPathValue.startsWith("/")) {
            outputPathValue = outputPathValue.substring(1)
        }
        def preferenceVO = new PreferenceVO()
        preferenceVO.setUsername(DBConstants.DB_DEFAULT_USERNAME)
        preferenceVO.setPassword(DBConstants.DB_DEFAULT_PASSWORD)
        preferenceVO.setUrl(DBConstants.DB_DEFAULT_URL)
        preferenceVO.setDriver(DBConstants.DB_DEFAULT_DRIVER)
        preferenceVO.setAuthor(GeneratorConstants.DEFAULT_AUTHOR)
        preferenceVO.setPackagePath(GeneratorConstants.DEFAULT_PACKAGE_PATH)
        preferenceVO.setEntitySuffix(GeneratorConstants.DEFAULT_ENTITY_SUFFIX)
        preferenceVO.setCommonPackage(GeneratorConstants.DEFAULT_COMMON_PACKAGE_PATH)
        preferenceVO.setOutputPath(outputPathValue)

        return preferenceVO
    }

    /**
     * 读取首选项配置值-packagePath,如果没有配置文件则取默认值
     *
     * @return - packagePath
     */
    static String readPackagePathValue() {
        def preferenceVO = readPreferenceProperties()
        if (preferenceVO != null) {
            return preferenceVO.getPackagePath()
        }
        return null
    }

    /**
     * 根据路径创建该文件所在的文件夹,如果文件夹存在就不创建
     *
     * @param filePath - 文件或文件夹路径
     * @param isFile - 是否未文件: true 文件, false 文件夹
     */
    static void createFileOrFolder(String filePath, boolean isFile) {
        def file = new File(filePath)
        def folder
        if (!file.exists()) {
            if (isFile) {
                folder = new File(filePath.substring(0, filePath.lastIndexOf("/")))
            } else {
                folder = file
            }
            if (!folder.exists() || !folder.isDirectory()) {
                folder.mkdirs()
            }
        }
    }

    /**
     * 创建数据库表设置表的一行
     *
     * @param item - 行数据
     * @param table - 表格对象
     * @param tableControls - 表格控件
     */
    static void createOneItemCells(TableItem item, Table table, Hashtable<TableItem, TableItemControl> tableControls) {
        // 复选框的控件
        def checkEditor = new TableEditor(table)
        def checkButton = new Button(table, SWT.CHECK)
        def isCheck = item.getText(DBConstants.CHECK_INDEX)
        if (StringUtils.equals("1", isCheck)) {
            checkButton.setSelection(true)
        } else {
            checkButton.setSelection(false)
        }
        checkEditor.grabHorizontal = true
        checkEditor.setEditor(checkButton, item, DBConstants.CHECK_INDEX)

        // 数据库表名的控件
        def tableNameEditor = new TableEditor(table)
        def tableNameText = new Text(table, SWT.BORDER)
        tableNameText.setText(item.getText(DBConstants.TABLE_NAME_INDEX))
        tableNameEditor.grabHorizontal = true
        tableNameEditor.setEditor(tableNameText, item, DBConstants.TABLE_NAME_INDEX)

        // 包路径的控件
        def classPathEditor = new TableEditor(table)
        def classPathText = new Text(table, SWT.BORDER)
        classPathText.setText(item.getText(DBConstants.CLASS_PATH_INDEX))
        classPathEditor.grabHorizontal = true
        classPathEditor.setEditor(classPathText, item, DBConstants.CLASS_PATH_INDEX)

        def tableItemControls = new TableItemControl(tableNameText, classPathText, checkButton, tableNameEditor, classPathEditor, checkEditor)
        tableControls.put(item, tableControls)
    }

}
